package com.cloudream.core.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;

public class WebLinkUtils {

    public static String getFileSha1(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[8192];
        int len;
        try {
            digest =MessageDigest.getInstance("SHA-1");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String doURL(String path) {
        StringBuffer rtn = new StringBuffer();
        try {
            URL url = new URL(path);
            try (InputStream in = url.openStream();
                 InputStreamReader isr = new InputStreamReader(in);
                 BufferedReader bufr = new BufferedReader(isr);) {
                String str;
                while ((str = bufr.readLine()) != null) {
                    rtn.append(str);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtn.toString();
    }

    public static String doURLConnection(String path, String cookie) {
        return doURLConnection(path, "UTF-8", cookie);
    }

    public static String doURLConnection(String path) {
        return doURLConnection(path, "UTF-8", null);
    }

    public static String doURLConnection(String path, String charset, String cookie) {
        StringBuffer rtn = new StringBuffer();
        try {
            URL url = new URL(path);
            URLConnection URLconnection = url.openConnection();
            if (cookie != null) {
                URLconnection.setRequestProperty("Cookie", cookie);
            }
            URLconnection.setRequestProperty("Accept-Charset", charset);
            URLconnection.setRequestProperty("contentType", charset);
            URLconnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=" + charset);
            URLconnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            URLconnection.setRequestProperty("Connection", "Keep-Alive");
            HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
//				System.err.println("连接成功");
                try (InputStream in = httpConnection.getInputStream();
                     InputStreamReader isr = new InputStreamReader(in, charset);
                     BufferedReader bufr = new BufferedReader(isr);) {
                    String str;
                    while ((str = bufr.readLine()) != null) {
                        rtn.append(str);
                    }
                }
            } else {
                if (responseCode != 404)
                    System.err.println("连接失败,CODE:" + responseCode + ";url:" + path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtn.toString();
    }

    public static String doHttpClient(String path) {
        HttpGet httpGet = new HttpGet(path);

        // 响应内容
        String responseContent = null;
        try (
                CloseableHttpClient httpClient = HttpClients.custom().build();
                CloseableHttpResponse response = httpClient.execute(httpGet);
        ) {
            HttpEntity entity = response.getEntity();
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                responseContent = EntityUtils.toString(entity, "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseContent;
    }

    public static String doUrlDownloadPlus(String urlStr, Object fileName, String savePath) {
        int core = urlStr.lastIndexOf(".");
        if (core > 0) {
            String exf = urlStr.substring(core);
            if (exf.indexOf("?") > 0) {
                exf = exf.substring(0, exf.indexOf("?"));
            }
            fileName = fileName + exf;
        }
        return doUrlDownload(urlStr, fileName, savePath);
    }

    public static String doUrlDownload(String urlStr, Object fileName, String savePath) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            // 文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            try (InputStream inputStream = conn.getInputStream();
                 FileOutputStream fos = new FileOutputStream(file);) {
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
            }
            return file.getPath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void outputFile(HttpServletResponse httpServletResponse, String path) {
        File file = new File(path);
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = httpServletResponse.getOutputStream();) {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (Exception e) {
            System.out.println("outputFile error ！ path：" + path);
        }
    }

}
